package com.dk.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //shiro的过滤器
        /*
        * anon : 无需认证直接放过
        * authc : 表示必须认证才能访问
        * perms : 表示当前的方法必须有XX个权限才能访问
        * logout : 退出登录过滤器
        * */
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/routeController/index","anon");
        map.put("/person/login","anon");
        map.put("/code/vcode","anon");
        map.put("/js/**","anon");
//        map.put("/loginController/login","anon");
        map.put("/logout","logout");
//        map.put("/crudController/add","perms[add]");
        map.put("/menu/show","perms[E]");
        map.put("/role/toAdd","perms[H]");
        map.put("/person/toAdd","perms[Y]");
        map.put("/**","authc");
        shiroFilterFactoryBean.setLoginUrl("/routeController/index");
        //配置自定义错误页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/routeController/unauthorized");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    //创建安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //安全管理器需要关联登录和授权的这些功能
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //创建自定义loginRealm
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    //开启shiro的密码加密功能
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密方式
        matcher.setHashAlgorithmName("MD5");
        //加密(撒盐)的次数
        matcher.setHashIterations(10);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
